<!--京东账单-->
<script setup lang="ts">
import {AxiosPromise} from "axios";

defineOptions({
	name: "JdBill",
	inheritAttrs: false,
});

import {ElLoading, UploadFile} from "element-plus";
import {
	getJdBillPage,
	getJdBillForm,
	saveJdBill,
	deleteJdBill,
	importJdBill,
	exportJdBill
} from "@/api/jdBill";
import {listAll} from "@/api/store";
import {StoreForm} from "@/api/store/types";
import lodash from "lodash-es";

const queryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);
const importRef = ref(ElForm);

const loading = ref(false);
const ids = ref<number[]>([]);
const total = ref(0);
const monthList = ref<[]>([]);
const importParams = reactive<any>({});
const storeList = ref<StoreForm[]>();

const queryParams = reactive<any>({
	pageNum: 1,
	pageSize: 20,
});

const jdBillList = ref<[]>();

const dialog = reactive<DialogOption>({
	visible: false,
});
const importDialog = reactive<DialogOption>({
	title: "京东结算单数据导入",
	visible: false,
});

const excelFile = ref<File>();
const excelFilelist = ref<File[]>([]);
const formData = reactive<any>({});

const rules = reactive({
	orderNo: [{ required: true, message: "请输入订单编号", trigger: "blur" }],
	orderCode: [{ required: true, message: "请输入单据编号", trigger: "blur" }],
	orderType: [{ required: true, message: "请输入单据类型", trigger: "blur" }],
	goodsNo: [{ required: true, message: "请输入商品编号", trigger: "blur" }],
	shopNo: [{ required: true, message: "请输入商户订单号", trigger: "blur" }],
	goodsName: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
	feeCreateTime: [{ required: true, message: "请输入费用发生时间", trigger: "blur" }],
	feeTime: [{ required: true, message: "请输入费用计费时间", trigger: "blur" }],
	settlementTime: [{ required: true, message: "请输入费用结算时间", trigger: "blur" }],
	feeType: [{ required: true, message: "请输入费用项", trigger: "blur" }],
	price: [{ required: true, message: "请输入金额", trigger: "blur" }],
	currency: [{ required: true, message: "请输入币种", trigger: "blur" }],
	receiveType: [{ required: true, message: "请输入商家应收/应付", trigger: "blur" }],
	shopCode: [{ required: true, message: "请输入店铺号", trigger: "blur" }],
	incomeType: [{ required: true, message: "请输入收支方向", trigger: "blur" }],
	billDate: [{ required: true, message: "请输入账单日期", trigger: "blur" }],
	quantity: [{ required: true, message: "请输入商品数量", trigger: "blur" }],
	createBy: [{ required: true, message: "请输入", trigger: "blur" }],
	updateBy: [{ required: true, message: "请输入", trigger: "blur" }],
	platform: [{ required: true, message: "请输入所属平台", trigger: "blur" }],
	storeId: [{ required: true, message: "请输入店铺ID", trigger: "blur" }],
});

const importRules = reactive({
	storeCode: [{ required: true, message: "请选择店铺", trigger: "change" }]
});




/**
 * 查询
 */
function handleQuery() {
	loading.value = true;
	if (lodash.size(monthList.value) > 0){
		lodash.set(queryParams, 'startMonth', monthList.value[0])
		lodash.set(queryParams, 'endMonth', monthList.value[1])
	}
	getJdBillPage(queryParams)
		.then(({ data }) => {
			jdBillList.value = data.list;
			total.value = data.total;
		})
		.finally(() => {
			loading.value = false;
		});
}

/**
 * 重置查询
 */
function resetQuery() {
	queryFormRef.value.resetFields();
	queryParams.pageNum = 1;
	handleQuery();
}

/**
 * 行checkbox change事件
 */
function handleSelectionChange(selection: any) {
	ids.value = selection.map((item: any) => item.id);
}

/**
 * 打开字典类型表单弹窗
 *
 * @param dicTypeId 字典类型ID
 */
function openDialog(id?: number) {
	dialog.visible = true;
	if (id) {
		dialog.title = "修改京东账单";
		getJdBillForm(id).then(({ data }) => {
			Object.assign(formData, data);
		});
	} else {
		dialog.title = "新增京东账单";
	}
}

/**
 * 字典类型表单提交
 */
function handleSubmit() {
	dataFormRef.value.validate((isValid: boolean) => {
		if (isValid) {
			loading.value = false;
			saveJdBill(formData)
				.then(() => {
					ElMessage.success("保存成功");
					closeDialog();
					handleQuery();
				})
				.finally(() => (loading.value = false));
		}
	});
}

/**
 * 关闭弹窗
 */
function closeDialog() {
	dialog.visible = false;
	resetForm();
}

/**
 * 重置表单
 */
function resetForm() {
	dataFormRef.value.resetFields();
	dataFormRef.value.clearValidate();

	formData.id = undefined;
}

/**
 * 删除京东账单
 */
function handleDelete(id?: number) {
	const dictTypeIds = [id || ids.value].join(",");
	if (!dictTypeIds) {
		ElMessage.warning("请勾选删除项");
		return;
	}

	ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
		confirmButtonText: "确定",
		cancelButtonText: "取消",
		type: "warning",
	}).then(() => {
		deleteJdBill(dictTypeIds).then(() => {
			ElMessage.success("删除成功");
			resetQuery();
		});
	});
}

/** 打开导入弹窗 */
async function openImportDialog() {
	getAllStore()
	importDialog.visible = true;
}

/**
 * Excel文件change事件
 *
 * @param file
 */
function handleExcelChange(file: UploadFile) {
	if (file.size !== undefined) {
		if (file.size > 20*1024*1024) {
			ElMessage.warning("上传文件大小已经超过20M，请尝试拆分成多个文件再上传");
			return false
		}
	}
	if (!/\.(csv|xlsx|xls|XLSX|XLS|CSV)$/.test(file.name)) {
		ElMessage.warning("上传Excel只能为xlsx、xls、csv格式");
		excelFile.value = undefined;
		excelFilelist.value = [];
		return false;
	}
	excelFile.value = file.raw;
}

/** 导入提交 */
function handleImport() {
	if (!excelFile.value) {
		ElMessage.warning("上传Excel文件不能为空");
		return false;
	}
	importRef.value.validate((isValid: boolean) => {
		if (isValid) {
			const importLoading = ElLoading.service({
				lock: true,
				text: '导入中...',
				background: 'rgba(0, 0, 0, 0.7)',
			})
			importJdBill(excelFile.value, importParams.storeCode).then((response) => {

				closeImportDialog();
				ElMessage.success('导入成功');
				resetQuery();
			}).finally(() => importLoading.close());
		}
	})
}

/**  关闭导入弹窗 */
function closeImportDialog() {
	importDialog.visible = false;
	excelFile.value = undefined;
	excelFilelist.value = [];
}

/** 导出京东账单 */
function handleExport() {
	const strIds = [ids.value].join(",");
	exportJdBill(strIds).then((response: any) => {
		const blob = new Blob([response.data], {
			type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",
		});
		const a = document.createElement("a");
		const href = window.URL.createObjectURL(blob); // 下载的链接
		a.href = href;
		a.download = decodeURI(
			response.headers["content-disposition"].split(";")[1].split("=")[1]
		); // 获取后台设置的文件名称
		document.body.appendChild(a);
		a.click(); // 点击导出
		document.body.removeChild(a); // 下载完成移除元素
		window.URL.revokeObjectURL(href); // 释放掉blob对象
	});
}

function getAllStore() {
	listAll().then((response) => {
		storeList.value = []
		const group_store = lodash.groupBy(response.data, 'storeKeyName');
		for (let key in group_store) {
			storeList.value.push({'label': key, 'options': group_store[key]})
		}
	})
}

onMounted(() => {
	let now = new Date()
	let month = now.getMonth()
	let nowMonth;
	if (month < 9){
		nowMonth = now.getFullYear() + '0' + (now.getMonth() + 1) + ''
	}	else {
		nowMonth = now.getFullYear() + '' + (now.getMonth() + 1) + ''
	}
	monthList.value = [nowMonth, nowMonth]
	handleQuery();
	getAllStore()
});
</script>

<template>
	<div class="app-container">
		<div class="search-container">
		  <el-form ref="queryFormRef" :model="queryParams" :inline="true">
				<el-form-item label="查询月份">
					<el-date-picker
							style="width: 200px"
							v-model="monthList"
							type="monthrange"
							range-separator="至"
							start-placeholder="开始月份"
							end-placeholder="结束月份"
							value-format="YYYYMM"
							:clearable="false"
					/>
				</el-form-item>
				<el-form-item label="店铺名称" prop="storeId">
					<el-select class="yz-el-select" v-model="queryParams.storeId" filterable placeholder="请选择店铺">
						<el-option-group
								v-for="group in storeList"
								:key="group.label"
								:label="group.label"
						>
							<el-option
									v-for="item in group.options"
									:key="item.id"
									:label="item.innerSystemStoreName"
									:value="item.id"
							/>
						</el-option-group>
					</el-select>
				</el-form-item>
				<el-form-item label="订单编号" prop="orderNo">
					<el-input
							v-model="queryParams.orderNo"
							placeholder="请输入订单编号"
							clearable
							style="width: 200px"
							@keyup.enter="handleQuery"
					/>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleQuery()"
					><i-ep-search />搜索</el-button
					>
					<el-button @click="resetQuery()"><i-ep-refresh />重置</el-button>
				</el-form-item>
			</el-form>
		</div>

		<el-card shadow="never">
			<template #header>
				<div class="flex justify-between">
					<div>
						<el-button
								v-hasPerm="['sys:jdBill:save']"
								type="success"
								@click="openDialog()"
						><i-ep-plus />新增</el-button
						>
						<el-button
								type="danger"
								:disabled="ids.length === 0"
								@click="handleDelete()"
								v-hasPerm="['sys:jdBill:delete']"
						><i-ep-delete />删除</el-button
						>
					</div>
					<div>
						<el-button class="ml-3" @click="openImportDialog" v-hasPerm="['sys:jdBill:import']"
						><template #icon><i-ep-top /></template>导入</el-button
						>
						<el-button class="ml-3" @click="handleExport" v-hasPerm="['sys:jdBill:export']"
						><template #icon><i-ep-download /></template>导出</el-button
						>
					</div>
				</div>
			</template>
			<el-table
					size="small"
					:header-row-style="{color: 'dimgray'}"
					v-loading="loading"
					highlight-current-row
					:data="jdBillList"
					border
					@selection-change="handleSelectionChange"
					:height="jdBillList && jdBillList.length > 0 ? 600 : 130"
			>
				<el-table-column label="订单编号" prop="orderNo" width="100" show-overflow-tooltip/>
				<el-table-column label="店铺名称" prop="storeName" width="100" show-overflow-tooltip/>
				<el-table-column label="单据编号" prop="orderNo" width="100" show-overflow-tooltip/>
				<el-table-column label="单据类型" prop="documentType" width="100" show-overflow-tooltip/>
				<el-table-column label="商品编号" prop="productCode" width="100" show-overflow-tooltip/>
				<el-table-column label="商户订单号" prop="sellerNo" width="100" show-overflow-tooltip/>
				<el-table-column label="商品名称" prop="productName" width="100" show-overflow-tooltip/>
				<el-table-column label="费用发生时间" prop="feeHappenTime" width="140" show-overflow-tooltip/>
				<el-table-column label="费用计费时间" prop="feeCalculateTime" width="140" show-overflow-tooltip/>
				<el-table-column label="费用结算时间" prop="feeSettlementTime" width="140" show-overflow-tooltip/>
				<el-table-column label="费用项" prop="feeProject" width="100" show-overflow-tooltip/>
				<el-table-column label="金额" prop="feeAmount" width="100" show-overflow-tooltip/>
				<el-table-column label="币种" prop="currency" width="100" show-overflow-tooltip/>
				<el-table-column label="商家应收/应付" prop="sellerReceivePay" width="100" show-overflow-tooltip/>
				<el-table-column label="钱包结算备注" prop="settlementRemark" width="100" show-overflow-tooltip/>
				<el-table-column label="店铺号" prop="storeNo" width="100" show-overflow-tooltip/>
				<el-table-column label="京东门店编号" prop="jdStoreNo" width="100" show-overflow-tooltip/>
				<el-table-column label="品牌门店编号" prop="brandStoreNo" width="100" show-overflow-tooltip/>
				<el-table-column label="门店名称" prop="shopName" width="100" show-overflow-tooltip/>
				<el-table-column label="备注" prop="remark" width="100" show-overflow-tooltip/>
				<el-table-column label="收支方向" prop="direction" width="100" show-overflow-tooltip/>
				<el-table-column label="账单日期" prop="billDate" width="100" show-overflow-tooltip/>
				<el-table-column label="商品数量" prop="qty" width="100" show-overflow-tooltip/>
			</el-table>

			<pagination
					v-if="total > 0"
					v-model:total="total"
					v-model:page="queryParams.pageNum"
					v-model:limit="queryParams.pageSize"
					@pagination="handleQuery"
			/>
		</el-card>

		<el-dialog
				v-model="dialog.visible"
				:title="dialog.title"
				width="500px"
				:close-on-click-modal="false"
				@close="closeDialog"
		>
			<el-form
					ref="dataFormRef"
					:model="formData"
					:rules="rules"
					label-width="150px"
			>
				<el-form-item label="订单编号" prop="orderNo">
					<el-input v-model="formData.orderNo" placeholder="请输入订单编号" clearable/>
				</el-form-item>
				<el-form-item label="单据编号" prop="orderCode">
					<el-input v-model="formData.orderCode" placeholder="请输入单据编号" clearable/>
				</el-form-item>
				<el-form-item label="单据类型" prop="orderType">
					<el-input v-model="formData.orderType" placeholder="请输入单据类型" clearable/>
				</el-form-item>
				<el-form-item label="商品编号" prop="goodsNo">
					<el-input v-model="formData.goodsNo" placeholder="请输入商品编号" clearable/>
				</el-form-item>
				<el-form-item label="商户订单号" prop="shopNo">
					<el-input v-model="formData.shopNo" placeholder="请输入商户订单号" clearable/>
				</el-form-item>
				<el-form-item label="商品名称" prop="goodsName">
					<el-input v-model="formData.goodsName" placeholder="请输入商品名称" clearable/>
				</el-form-item>
				<el-form-item label="费用发生时间" prop="feeCreateTime">
					<el-input v-model="formData.feeCreateTime" placeholder="请输入费用发生时间" clearable/>
				</el-form-item>
				<el-form-item label="费用计费时间" prop="feeTime">
					<el-input v-model="formData.feeTime" placeholder="请输入费用计费时间" clearable/>
				</el-form-item>
				<el-form-item label="费用结算时间" prop="settlementTime">
					<el-input v-model="formData.settlementTime" placeholder="请输入费用结算时间" clearable/>
				</el-form-item>
				<el-form-item label="费用项" prop="feeType">
					<el-input v-model="formData.feeType" placeholder="请输入费用项" clearable/>
				</el-form-item>
				<el-form-item label="金额" prop="price">
					<el-input v-model="formData.price" placeholder="请输入金额" clearable/>
				</el-form-item>
				<el-form-item label="币种" prop="currency">
					<el-input v-model="formData.currency" placeholder="请输入币种" clearable/>
				</el-form-item>
				<el-form-item label="商家应收/应付" prop="receiveType">
					<el-input v-model="formData.receiveType" placeholder="请输入商家应收/应付" clearable/>
				</el-form-item>
				<el-form-item label="店铺号" prop="shopCode">
					<el-input v-model="formData.shopCode" placeholder="请输入店铺号" clearable/>
				</el-form-item>
				<el-form-item label="收支方向" prop="incomeType">
					<el-input v-model="formData.incomeType" placeholder="请输入收支方向" clearable/>
				</el-form-item>
				<el-form-item label="账单日期" prop="billDate">
					<el-input v-model="formData.billDate" placeholder="请输入账单日期" clearable/>
				</el-form-item>
				<el-form-item label="商品数量" prop="quantity">
					<el-input v-model="formData.quantity" placeholder="请输入商品数量" clearable/>
				</el-form-item>
				<el-form-item label="" prop="createBy">
					<el-input v-model="formData.createBy" placeholder="请输入" clearable/>
				</el-form-item>
				<el-form-item label="" prop="updateBy">
					<el-input v-model="formData.updateBy" placeholder="请输入" clearable/>
				</el-form-item>
				<el-form-item label="所属平台" prop="platform">
					<el-input v-model="formData.platform" placeholder="请输入所属平台" clearable/>
				</el-form-item>
				<el-form-item label="店铺ID" prop="storeId">
					<el-input v-model="formData.storeId" placeholder="请输入店铺ID" clearable/>
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" @click="handleSubmit">确 定</el-button>
					<el-button @click="closeDialog">取 消</el-button>
				</div>
			</template>
		</el-dialog>

		<!-- 导入弹窗 -->
		<el-dialog
				v-model="importDialog.visible"
				:title="importDialog.title"
				width="600px"
				append-to-body
				@close="closeImportDialog"
		>
			<el-form label-width="80px" :model="importParams" :rules="importRules" ref="importRef">
				<el-form-item label="店铺" prop="storeCode">
					<el-select class="yz-el-select" v-model="importParams.storeCode" filterable clearable placeholder="请选择店铺">
						<el-option-group
								v-for="group in storeList"
								:key="group.label"
								:label="group.label"
						>
							<el-option
									v-for="item in group.options"
									:key="item.id"
									:label="item.innerSystemStoreName"
									:value="item.commercePlatformStoreCode"
							/>
						</el-option-group>
					</el-select>
				</el-form-item>
				<el-form-item label="Excel">
					<el-upload
							class="upload-demo"
							action=""
							drag
							:auto-upload="false"
							accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
							:file-list="excelFilelist"
							:on-change="handleExcelChange"
							:limit="1"
					>
						<el-icon class="el-icon--upload">
							<i-ep-upload-filled/>
						</el-icon>
						<div class="el-upload__text">
							将文件拖到此处，或
							<em>点击上传</em>
						</div>
						<template #tip>
							<div class="el-upload__tip">xls/xlsx files</div>
						</template>
					</el-upload>
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" @click="handleImport">确 定</el-button>
					<el-button @click="closeImportDialog">取 消</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>
